import { Button, Form, Input, Space, message } from "antd";
import { Component, createRef } from "react";
import { type RouteComponentProps } from "react-router-dom";
import { connect, type ConnectedProps } from "react-redux";
import Captcha, { type CaptchaInstance } from "@/components/captcha";

// 引入 login 这个动作创建函数
import { login } from "@/store/modules/user";

import style from "./index.module.scss";

class Login extends Component<PropsFromRedux & RouteComponentProps> {
  captchaRef = createRef<CaptchaInstance>();

  onFinish = async (values: Login.Params) => {
    // 组装出登录接口需要的参数
    const params = {
      ...values,
      captchaId: this.captchaRef.current?.get() as string,
    };

    try {
      // 派发一个 login 动作
      //  unwrap() 主要是解开 异步动作的 Promise 包装，如果不解开的话，我们无法得知异步动作里面抛出的错误
      // await this.props.dispatch(login(params)).unwrap();
      await this.props.handleLogin(params).unwrap();
      message.success({
        content: "登录成功",
        duration: 0.1,
        onClose: () => {
          // 获取到 redirect
          const searchParams = new URLSearchParams(this.props.location.search);
          const redirect = searchParams.get("redirect") || "/";
          // 跳转到首页
          this.props.history.replace(redirect);
        },
      });
    } catch (error) {
      console.log("登录失败");
      // 需要让 Captcha 组件刷新验证码
      this.captchaRef.current?.refresh();
    }
  };

  render() {
    return (
      <div className={style.page}>
        <Form
          className={style.form}
          initialValues={{ username: "admin", password: "123456" }}
          onFinish={this.onFinish}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input placeholder="用户名" />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password placeholder="密码" />
          </Form.Item>

          <Form.Item
            name="verifyCode"
            rules={[{ required: true, message: "请输入验证码" }]}
          >
            <Space>
              <Input placeholder="验证码" />
              <Captcha ref={this.captchaRef} />
            </Space>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              Submit
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}

const connector = connect(null, {
  handleLogin: (params: Login.Params) => login(params),
});

// 根据 connector 使用 ConnectedProps 算出 props 的类型
type PropsFromRedux = ConnectedProps<typeof connector>;

export default connector(Login);
